//#define QT_NO_CAST_FROM_ASCII

#include "uploader.h"
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QUrl>
#include <QFileInfo>
#include <QtConcurrentRun>
#include <QFuture>

#include <QDebug>

Uploader::Uploader()
{

}

QString Uploader::uploadImage(QString filePath) {
    uploadFile(filePath);

    loop.exec();

    return resultUrl;
}

void Uploader::uploadFile(QString filePath) {
    QNetworkAccessManager* manager = new QNetworkAccessManager();

    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
    connect(this, SIGNAL(resultUrlReady(QString)), this, SLOT(resultUrlParsed(QString)));
    connect(this, SIGNAL(error(QString)), this, SLOT(parsingUrlError(QString)));

    QNetworkRequest request(QUrl("http://imageshack.us/upload_api.php"));

    QString boundary = "MYOWNBOUNDARY";
    QByteArray data = preparePostData(filePath, boundary);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary);
    request.setHeader(QNetworkRequest::ContentLengthHeader, QString::number(data.length()));
    request.setRawHeader("Connection","keep-alive");

    QNetworkReply *reply = manager->post(request, data);
}

QByteArray Uploader::preparePostData(QString filePath, QString boundary) {
    QFile sourceFile(filePath);
    QFileInfo fileInfo(filePath);

    QByteArray fileData;
    QByteArray dataToSend;

    if(sourceFile.open(QFile::ReadOnly)) {
        fileData = sourceFile.readAll();

        sourceFile.close();
    }
    else {
        emit error(QString("Could not open file"));

        return QByteArray();
    }

    QString crlf = "\r\n";

    dataToSend.append(QString("--").toAscii());
    dataToSend.append(boundary.toAscii());
    dataToSend.append(crlf.toAscii());

    dataToSend.append(QString("Content-Disposition: form-data; name=\"fileupload\"; filename=\"%1\"").arg(fileInfo.fileName()).toAscii());
    dataToSend.append(crlf.toAscii());
    dataToSend.append(QString("Content-Type: image/%1").arg(fileInfo.suffix().toLower()).toAscii());

    dataToSend.append(crlf.toAscii());
    dataToSend.append(crlf.toAscii());

    dataToSend.append(fileData);

    dataToSend.append(crlf.toAscii());
    dataToSend.append(QString("--").toAscii());
    dataToSend.append(boundary.toAscii());
    dataToSend.append(QString("--").toAscii());
    dataToSend.append(crlf.toAscii());

    return dataToSend;
}

void Uploader::replyFinished(QNetworkReply *reply) {
    QString replyString = reply->readAll();

    if(replyString.size() == 0) {
        emit error(QString("Http reply is empty"));

        return;
    }

    int linkStartPosition = replyString.indexOf("<image_link>");
    int linkStopPosition = replyString.indexOf("</image_link>");
    int size = QString("<image_link>").length();
    QString resultUrlStr = replyString.mid(linkStartPosition + size, linkStopPosition - linkStartPosition - size);

    if(resultUrlStr.size() == 0) {
        emit error(QString("Could not parse image url from reply"));

        return;
    }

    emit resultUrlReady(resultUrlStr);
}

void Uploader::resultUrlParsed(QString url) {
    this->resultUrl = url;

    loop.exit();
}

void Uploader::parsingUrlError(QString errorMsg) {
    qDebug() << errorMsg;

    loop.exit();
}
